package com.bp.hearthealth.pulse.lnapps.bp_utils

import android.animation.Animator
import android.animation.ValueAnimator
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil

class ProgressBarUpdater(
    private val totalDuration: Long,
    private val onUpdate: (Int) -> Unit,
    private val onAnimationEnd: () -> Unit
) {

    private var canceled = false
    private var listener = false
    private lateinit var valueAnimator: ValueAnimator


    fun setupAnimator() {
        valueAnimator = ValueAnimator.ofInt(0, 100)
        valueAnimator.duration = totalDuration
        valueAnimator.addUpdateListener { animator ->
            val animatedValue = animator.animatedValue as Int
            if (animatedValue != 0) {
                onUpdate(animatedValue)
            }
            //animatedValue==0 会回调多次，会随机性的调用onAnimationEnd回调，所以此处需onAnimationEnd>0时设置监听
            if (animatedValue > 0) {
                if (!listener) {
                    valueAnimator.addListener(object : Animator.AnimatorListener {
                        override fun onAnimationStart(animation: Animator) {}
                        override fun onAnimationEnd(animation: Animator) {
                            if (!canceled) {
                                LogUtil.i("ProgressBarUpdater：onAnimationEnd")
                                onAnimationEnd()
                            }
                        }

                        override fun onAnimationCancel(animation: Animator) {
                        }

                        override fun onAnimationRepeat(animation: Animator) {}
                    })
                    listener = true
                }
            }
        }



        canceled = false
        valueAnimator.start()
//        LogUtil.i("valueAnimator.start()")
    }

    fun setCanceledState(canceledState: Boolean) {
        canceled = canceledState
    }

    fun cancel() {
        canceled = true
    }

    fun simulateAnimationEnd() {
        onAnimationEnd()
    }

    fun release() {
        valueAnimator.removeUpdateListener(null)
        valueAnimator.removeAllUpdateListeners()
        valueAnimator.cancel()
    }
}
